package com.star.uc.factory.login.impl;

import com.aliyun.dypnsapi20170525.models.GetSmsAuthTokensResponse;
import com.star.common.core.contract.exception.ServiceException;
import com.star.common.core.operator.OperatorRouter;
import com.star.common.core.utils.BizAssert;
import com.star.uc.contract.dto.request.LoginRequest;
import com.star.uc.contract.enums.ClientTypeEnum;
import com.star.uc.contract.enums.LoginTypeEnum;
import com.star.uc.contract.enums.UserErrorEnum;
import com.star.uc.factory.login.AbstractLoginTypeOperator;
import com.star.uc.infras.properties.AlibabaProperties;
import com.star.uc.infras.repository.model.UserInfoBO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 一键快速登录
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/10/19 17:31
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OneClickPhoneLoginTypeOperator extends AbstractLoginTypeOperator {

    private final AlibabaProperties alibabaProperties;


    /**
     * Operator的名称, 同一类型的Operator的路由器{@link OperatorRouter}能够根据该值路由到当前的Operator
     *
     * @return route key
     */
    @Override
    public String getName() {
        return LoginTypeEnum.ONE_CLICK_PHONE.getCode();
    }

    /**
     * 检查对应的登录类型的参数
     *
     * @param loginRequest
     */
    @Override
    public void checkParam(LoginRequest loginRequest) {
        BizAssert.notNullWarn(loginRequest.getOneClickPhoneRequest(), UserErrorEnum.ONE_CLICK_PHONE_REQUEST_ERROR);
        BizAssert.notBlankWarn(loginRequest.getOneClickPhoneRequest().getSignName(), UserErrorEnum.SIGN_NAME);
        BizAssert.notBlankWarn(loginRequest.getOneClickPhoneRequest().getSceneCode(), UserErrorEnum.SCENE_CODE);
        BizAssert.notNullWarn(loginRequest.getOneClickPhoneRequest().getExpire(), UserErrorEnum.EXPIRE);
        BizAssert.notNullWarn(loginRequest.getOneClickPhoneRequest().getSmsCodeExpire(), UserErrorEnum.SMS_CODE_EXPIRE);
        BizAssert.notBlankWarn(loginRequest.getOneClickPhoneRequest().getSmsTemplateCode(), UserErrorEnum.SMS_TEMPLATE_CODE);
        if (ClientTypeEnum.IOS.getCode().equals(loginRequest.getClientType())) {

            BizAssert.notBlankWarn(loginRequest.getOneClickPhoneRequest().getIos().getBundleId(), UserErrorEnum.BUNDLE_ID);
        } else {
            BizAssert.notBlankWarn(loginRequest.getOneClickPhoneRequest().getAndroid().getPackageName(), UserErrorEnum.PAKAGE_NAME);
        }
    }

    /**
     * 登录
     *
     * @param loginRequest 登录请求/获取短信验证码授权Token
     * @return 用户信息
     */
    @Override
    public UserInfoBO authorize(LoginRequest loginRequest) {

        try {
            this.checkParam(loginRequest);
            // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
            if (Objects.isNull(alibabaProperties.getOneClick()) || StringUtils.isBlank(alibabaProperties.getOneClick().getAccessKeyId()) || StringUtils.isBlank(alibabaProperties.getOneClick().getAccessKeySecret())) {
                log.error("阿里巴巴一键登录配置为空");
                throw new ServiceException(UserErrorEnum.ALIBABA_ONE_CLICK_CONFIG_NULL);
            }
            com.aliyun.dypnsapi20170525.Client client = OneClickPhoneLoginTypeOperator.createClient(alibabaProperties.getOneClick().getAccessKeyId(), alibabaProperties.getOneClick().getAccessKeySecret());
            com.aliyun.dypnsapi20170525.models.GetSmsAuthTokensRequest getSmsAuthTokensRequest = new com.aliyun.dypnsapi20170525.models.GetSmsAuthTokensRequest();
            //getSmsAuthTokensRequest.setExpire(loginRequest.getExpire());
            //getSmsAuthTokensRequest.setBundleId(loginRequest.getBundleId());
            //getSmsAuthTokensRequest.setOsType(loginRequest.getOsType());
            //getSmsAuthTokensRequest.setPackageName(loginRequest.getPackageName());
            //getSmsAuthTokensRequest.setSignName(loginRequest.getSignName());
            //getSmsAuthTokensRequest.setSceneCode(loginRequest.getSceneCode());
            //getSmsAuthTokensRequest.setSmsCodeExpire(loginRequest.getSmsCodeExpire());
            //getSmsAuthTokensRequest.setSmsTemplateCode(loginRequest.getSmsTemplateCode());
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            // 复制代码运行请自行打印 API 的返回值
            GetSmsAuthTokensResponse response = client.getSmsAuthTokensWithOptions(getSmsAuthTokensRequest, runtime);


            //调完阿里云之后返回的一定是phone，手机号

            //拿到这个去UserOuterMapperInfoBO，登录类型：phone，去查手机号码有没有存在，已经存在的情况下，封装数据返回，不存在就创建用户，然后返回。

            //组装返回的客户端body
        } catch (Exception e) {
            throw new ServiceException(e);
        }
        return null;
    }

    /**
     * 获取阿里云客户端
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws Exception
     */
    public static com.aliyun.dypnsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dypnsapi
        config.endpoint = "dypnsapi.aliyuncs.com";
        return new com.aliyun.dypnsapi20170525.Client(config);
    }

    /**
     * 创建用户
     *
     * @param loginRequest 登录请求信息
     * @param authUser     第三方响应信息
     * @return 用户信息
     */
    @Override
    public UserInfoBO createUser(LoginRequest loginRequest, AuthUser authUser) {
        return super.createUser(loginRequest, authUser);
    }

    /**
     * 创建用户映射
     *
     * @param uid          用户ID
     * @param loginRequest 登录请求
     * @param authUser     第三方响应信息
     * @return 用户映射信息
     */
    @Override
    public void createUserMapping(String uid, LoginRequest loginRequest, AuthUser authUser) {
        super.createUserMapping(uid, loginRequest, authUser);
    }
}
